package com.example.yichuangyun.mvvm.ui.activity;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.media3.common.MediaItem;
import androidx.media3.common.PlaybackException;
import androidx.media3.common.Player;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.source.ProgressiveMediaSource;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityCallRecordBinding;
import com.example.yichuangyun.model.business.CallRecordDataModel;
import com.example.yichuangyun.model.call.TabModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.ui.activity.view.CallRecordViewModel;
import com.example.yichuangyun.mvvm.ui.fragment.CallDetailsAnalysisFragment;
import com.example.yichuangyun.mvvm.ui.fragment.CallDetailsTextFragment;
import com.example.yichuangyun.utils.ToastHelper;
import com.flyco.tablayout.listener.CustomTabEntity;

import java.util.ArrayList;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * 通话录音
 */
@SuppressLint("SetTextI18n")
public class CallRecordActivity extends BaseActivity<ActivityCallRecordBinding, CallRecordViewModel> {

    private final ArrayList<Fragment> fragments = new ArrayList<>();
    private final ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private ExoPlayer player;
    private Handler handler;
    private Runnable updateSeekBarRunnable;
    private String id;
    private int duration;

    private final int[] mIconSelectIds = {R.mipmap.icon_trans_text_sel, R.mipmap.icon_ai_sel};
    private final int[] mIconUnselectIds = {R.mipmap.icon_trans_text, R.mipmap.icon_ai};

    @Override
    protected CallRecordViewModel bindModel() {
        return getViewModel(this, CallRecordViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void initData() {
        initTitleBar(getString(R.string.call_record_details));
        handler = new Handler(Looper.getMainLooper());
        // 创建 ExoPlayer 实例
        player = new ExoPlayer.Builder(this).build();
        if (getIntent().getExtras() != null) {
            CallRecordDataModel.CallListModel.CallRecordModel callRecordModel = (CallRecordDataModel.CallListModel.CallRecordModel) getIntent().getExtras().getSerializable(Constant.modelKey);
            if (callRecordModel != null) {
                String telNumber = callRecordModel.getTelNumber();
                binding.tvTitle.setText(getString(R.string.user_sound_recording,
                        !TextUtils.isEmpty(callRecordModel.getUserName()) ?
                                callRecordModel.getUserName() + telNumber : telNumber));
                duration = callRecordModel.getCallSec();
                binding.tvDate.setText(callRecordModel.getTrackTime());
                id = callRecordModel.getId();

                int telType = callRecordModel.getTelType();
                String recordPath = callRecordModel.getRecfilepath();
                String linkedId = callRecordModel.getLinkedid();
                // 1管帮手，2电话系统，3AI外呼，10回拨1，12回拨2
                switch (telType) {
                    case 1: // 管帮手
                        if (!TextUtils.isEmpty(recordPath)) {
                            playAudio(recordPath); //云客（全路径）
                        } else {
                            viewModel.getPcRecordUrl(linkedId);
                        }
                        break;
                    case 2: // 电话系统（全路径）
                        if (!TextUtils.isEmpty(recordPath)) {
                            playAudio(recordPath);
                        }
                        break;
                    case 3: // AI外呼
                        if (!TextUtils.isEmpty(recordPath)) {
                            viewModel.getPcRecordUrl(recordPath);
                        }
                        break;
                    default:
                        if (!TextUtils.isEmpty(linkedId)) {
                            viewModel.getPcRecordUrl(linkedId);
                        }
                        break;
                }
            }
        }
    }

    private void initFragment(String url) {
        String[] mTitles = new String[]{getString(R.string.communication_records), getString(R.string.ai_analysis)};
        mTabEntities.add(new TabModel(mTitles[0], mIconSelectIds[0], mIconUnselectIds[0]));
        mTabEntities.add(new TabModel(mTitles[1], mIconSelectIds[1], mIconUnselectIds[1]));
        CallDetailsTextFragment textFragment = CallDetailsTextFragment.newInstance(id, url);
        CallDetailsAnalysisFragment analysisFragment = CallDetailsAnalysisFragment.newInstance(id, url, duration);
        fragments.add(textFragment);
        fragments.add(analysisFragment);
        binding.tabLayout.setTabData(mTabEntities, this, R.id.flChange, fragments);
    }

    @Override
    protected void initClick() {
        // 获取录音url成功
        viewModel.urlSuccess.observe(this, s -> {
            dismissLoadingDialog();
            playAudio(s);
        });

        // 获取录音文件失败
        viewModel.urlError.observe(this, s -> dismissLoadingDialog());

        // 播放/暂停
        viewModel.onDelayClick(binding.playIv, o -> {
            if (binding.tvTotal.getText().toString().equals(getString(R.string.def_recording_time))) {
                ToastHelper.show(getString(R.string.file_exception));
                return;
            }

            if (player.isPlaying()) {
                player.pause();
                handler.removeCallbacks(updateSeekBarRunnable);
                binding.playIv.setImageResource(R.mipmap.icon_play_record);
            } else {
                if (player.getPlaybackState() == Player.STATE_ENDED) {
                    // 如果播放已结束，重新开始播放
                    player.seekTo(0);
                }
                player.play();
                updateSeekBar();
                binding.playIv.setImageResource(R.mipmap.icon_pause_record);
            }
        });

        // 监听播放完成事件
        player.addListener(new Player.Listener() {
            @Override
            public void onPlaybackStateChanged(int playbackState) {
                if (playbackState == Player.STATE_ENDED) {
                    binding.playIv.setImageResource(R.mipmap.icon_play_record);
                }
            }

            @Override
            public void onPlayerError(@NonNull PlaybackException error) {
                binding.playIv.setImageResource(R.mipmap.icon_play_record);
            }
        });

        // 设置 SeekBar 监听器
        binding.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    player.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 停止更新 SeekBar
                handler.removeCallbacks(updateSeekBarRunnable);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 恢复更新 SeekBar
                updateSeekBar();
            }
        });
    }

    private void updateSeekBar() {
        if (player != null) {
            int currentPosition = (int) player.getCurrentPosition();
            int duration = (int) player.getDuration();
            binding.seekBar.setMax(duration);
            binding.seekBar.setProgress(currentPosition);
            binding.tvTotal.setText(formatDuration(duration));
            binding.tvLastTime.setText("-" + formatDuration(duration - currentPosition));
            binding.tvPlayTime.setText(formatDuration(currentPosition));
            updateSeekBarRunnable = new Runnable() {
                @Override
                public void run() {
                    updateSeekBar();
                }
            };
            handler.postDelayed(updateSeekBarRunnable, 1000);
        }
    }

    /**
     * 播放音频
     */
    @SuppressLint("UnsafeOptInUsageError")
    private void playAudio(String url) {
        if (TextUtils.isEmpty(url) || !url.startsWith("https://")) {
            return;
        }
        // 创建 DataSource
        DefaultDataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(this);
        // 创建 MediaSource
        ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(dataSourceFactory)
                .createMediaSource(MediaItem.fromUri(Uri.parse(url)));
        // 准备播放器
        player.setMediaSource(mediaSource);
        player.prepare();
        player.play();
        binding.playIv.setImageResource(R.mipmap.icon_pause_record);
        // 开始更新 SeekBar
        updateSeekBar();
        initFragment(url);
    }

    private String formatDuration(int duration) {
        long minutes = TimeUnit.MILLISECONDS.toMinutes(duration);
        long seconds = TimeUnit.MILLISECONDS.toSeconds(duration) - TimeUnit.MINUTES.toSeconds(minutes);
        return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            // 释放 ExoPlayer 资源
            player.release();
            player = null;
        }
        if (handler != null) {
            handler.removeCallbacks(updateSeekBarRunnable);
        }
    }
}